package com.wanghua.spring.filter.watermark;

import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import com.wanghua.spring.util.ImageUtil;

/*
* 由于自定义的 Response 只处理二进制图像数据，因此简单起见只覆盖了 getOutputStream() 方法。
* */
public class WaterMarkResponseWrapper extends HttpServletResponseWrapper {
	private String waterMarkFile;                          // 水印图片位置
	private HttpServletResponse response;                   // 原response
	private WaterMarkOutputStream waterMarkOutputStream;  // 自定义servletOutputStream，用于缓冲图像数据

	public WaterMarkResponseWrapper(HttpServletResponse response, String waterMarkFile) throws IOException {
		super(response);
		this.response = response;
		this.waterMarkFile = waterMarkFile;
		this.waterMarkOutputStream = new WaterMarkOutputStream();
	}

	@Override
	public ServletOutputStream getOutputStream() throws IOException {
		return waterMarkOutputStream;
	}

	@Override
	public void flushBuffer() throws IOException {
		waterMarkOutputStream.flush();
	}

	// 将图像数据打水印，并输出到客户端浏览器
	public void finishResponse() throws IOException {
		byte[] imageData = waterMarkOutputStream.getByteArrayOutputStream().toByteArray(); // 原图片数据
		byte[] image = ImageUtil.waterMark(imageData, waterMarkFile); // 打水印后的图片数据

		// 将图像输出到浏览器
		response.setContentLength(image.length);
		response.getOutputStream().write(image);

		waterMarkOutputStream.close();
	}
}
